import * as types from '../action-types'
import { setToken, removeToken } from '@/utils/auth'
import { reqLogin, reqUserInfo, reqLogout } from '../../api/user'
import store from '@/store'

// 登录
export const login = (username, password) => dispatch => {
  // reqLogin是一个promise需要返回结果值
  return reqLogin({ username, password })
    .then(result => {
      const { token } = result.data.data
      // 保存 token
      dispatch(setUserToken(token))
      setToken(token)
      return result
    })
    .catch(error => {
      throw error.message
    })
}

export const logout = token => dispatch => {
  return reqLogout()
    .then(result => {
      const { status } = result
      if (status === 200) {
        // 清除 token 重置用户信息
        dispatch(resetUser())
        removeToken()
      } else {
        reject(result.message)
      }
      return result
    })
    .catch(error => {
      throw error.message
    })
}

/**
 * 查询用户信息
 * @param {*} token
 * @returns
 */
export const getUserInfo = token => dispatch => {
  if (store.getState().user.name) return //避免获取用户信息死循环
  return reqUserInfo(token)
    .then(result => {
      // 获取头像,昵称,按钮权限,菜单权限,总权限
      // const { avatar, name, buttons, roles, routes } = result.data.data
      const userInfo = result.data.data
      // 设置用户信息
      dispatch(setUserInfo(userInfo))
      return result
    })
    .catch(error => {
      throw error.message
    })
}

export const setUserToken = token => {
  return {
    type: types.USER_SET_USER_TOKEN,
    token
  }
}

export const setUserInfo = userInfo => {
  return {
    type: types.USER_SET_USER_INFO,
    ...userInfo
  }
}

export const resetUser = () => {
  return {
    type: types.USER_RESET_USER
  }
}
